package com.easycarebn.service.request;

import android.content.Context;

import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.RetryPolicy;
import com.android.volley.toolbox.Volley;
import com.easycarebn.service.volley.ssl.SslHttpStack;

public class RequestManager {
    private static final String TAG = "ServerRequest";

    private static final int INITIAL_TIME_OUT = 30000; // 30secs
    private static final int MAX_NUM_RETRIES = 2;   // twice
    
    
    private RequestQueue mRequestQueue;
    private Context mContext;
    private RetryPolicy mRetryPolicy;

    private static RequestManager sInstance = null;

    private RequestManager(Context context) {
        mContext = context;
        mRetryPolicy = new DefaultRetryPolicy(INITIAL_TIME_OUT, MAX_NUM_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
    }

    public static RequestManager newInstance(Context context) {
        if (sInstance == null) {
            sInstance = new RequestManager(context);
        }
        return sInstance;
    }

    public RequestQueue getRequestQueue() {
        if (mRequestQueue == null) {
            mRequestQueue = Volley.newRequestQueue(mContext, new SslHttpStack(mContext, false));
        }

        return mRequestQueue;
    }

    public <T> void addToRequestQueue(Request<T> req) {
        req.setTag(TAG);
        req.setRetryPolicy(mRetryPolicy);
        getRequestQueue().add(req);
    }

    public void cancelPendingRequests(Object tag) {
        if (mRequestQueue != null) {
            mRequestQueue.cancelAll(tag);
        }
    }
}
